package com.taiyi.renaissancemall.ui.main.shoppingcar

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.*
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.liaoinstan.springview.container.DefaultFooter
import com.liaoinstan.springview.container.DefaultHeader
import com.liaoinstan.springview.widget.SpringView
import com.taiyi.renaissancemall.R
import com.taiyi.renaissancemall.Utils.ToastUtils
import com.taiyi.renaissancemall.Utils.load
import com.taiyi.renaissancemall.Utils.loadCircle
import com.taiyi.renaissancemall.base.BaseActivity
import com.taiyi.renaissancemall.bean.ShoppingCarListBean
import com.taiyi.renaissancemall.ui.main.order.FillOrderActivity
import kotlinx.android.synthetic.main.base_top_white_background_layout.*
import kotlinx.android.synthetic.main.shopping_cart_layout.*

class ShoppingCarActivity : BaseActivity<ShoppingCarView, ShoppingCarPresent>(), ShoppingCarView,
    SpringView.OnFreshListener {

    var isSelectAll: Boolean = false
    override fun getLayoutId(): Int = R.layout.shopping_cart_layout
    var data = mutableListOf<ShoppingCarListBean.CartListBean>()
    var ifHui = "1"
    var pageNum = 1
    var selShoppingCarIds = ""
    var updateShoppingCarId = 0
    var updateShoppingCarNum = 0
    override fun initPresenter(): ShoppingCarPresent = ShoppingCarPresent()


    override fun initViews(savedInstanceState: Bundle?) {
        titleTv.text = getString(R.string.shoppingCar)
        rightIv.setImageResource(R.mipmap.shopping_cart_right_iv)
        springView.header = DefaultHeader(this)
        springView.footer = DefaultFooter(this)
        springView.setGive(SpringView.Give.BOTH)
        springView.type = SpringView.Type.FOLLOW
        springView.setListener(this)

        shoppingCarRecyclerView.run {
            layoutManager = LinearLayoutManager(this@ShoppingCarActivity)
//            adapter = AdapterManager.getShoppingCarListAdapter(this@ShoppingCarActivity, data)
            adapter = MyAdapter(this@ShoppingCarActivity, data)
        }

    }


    inner class MyAdapter(context: Context, data1: MutableList<ShoppingCarListBean.CartListBean>) :
        RecyclerView.Adapter<MyAdapter.MyHolder>() {
        var layoutInflater: LayoutInflater = LayoutInflater.from(context)

        inner class MyHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val iv = itemView.findViewById<ImageView>(R.id.iv)
            val nameTv = itemView.findViewById<TextView>(R.id.nameTv)
            val selectTv = itemView.findViewById<TextView>(R.id.selectTv)
            val recyclerView = itemView.findViewById<RecyclerView>(R.id.recyclerView)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
            var view = layoutInflater.inflate(R.layout.shopping_car_item_layout, parent, false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int = when (data) {
            null -> 0
            else
            -> data.size
        }

        override fun onBindViewHolder(holder: MyHolder, position: Int) {
            holder.iv.loadCircle(data[position].logo)
            var detailList = data[position].details

            holder.selectTv.setOnClickListener {
                data[position].isSelectAll = !data[position].isSelectAll
                if (!data[position].isSelectAll) {
                    isSelectAll = data[position].isSelectAll
                    selectAllCb.isSelected = isSelectAll
                }
                holder.selectTv.isSelected = data[position].isSelectAll
                for (index in detailList.indices) {
                    detailList[index].isSelectState = data[position].isSelectAll
                }

                var k = 0//记录是否选中所有店铺
                for (i in data.indices) {
                    var selectAll = data[i].isSelectAll
                    if (selectAll) {
                        ++k
                    }
                }
                selectAllCb.isSelected = k == data.size

                notifyDataSetChanged()
            }


            var count = 0//记录当前店铺下选中的条目数
            for (index in detailList.indices) {
                if (detailList[index].isSelectState) ++count
            }
            if (count == detailList.size || isSelectAll) {
                data[position].isSelectAll = true
                holder.selectTv.isSelected = true
            } else {
                data[position].isSelectAll = false
                holder.selectTv.isSelected = false
            }

            var k = 0//记录是否选中所有店铺
            for (i in data.indices) {
                var selectAll = data[i].isSelectAll
                if (selectAll)
                    ++k
            }
            selectAllCb.isSelected = k == data.size

            var sumBv = 0.0
            var sumPrice = 0.0
            var selectNum = 0
            for (index in 0 until data.size) {
                var details = data[index].details
                for (k in details.indices) {
                    if (details[k].isSelectState) {
                        selectNum += 1
                        var bvPrice = details[k].bvprice
                        sumBv += bvPrice.toDouble() * details[k].number
                        sumPrice += if (ifHui == "1") {
                            var hyPrice = details[k].hyprice
                            hyPrice.toDouble() * details[k].number
                        } else {
                            var price = details[k].price
                            price.toDouble() * details[k].number
                        }
                    }
                }
            }
            if (selectType == 1) {//删除
                toSettlementTv.text = getString(R.string.toSettlement) + "($selectNum)"
            } else {
                toSettlementTv.text = getString(R.string.delete) + "($selectNum)"
            }
            totalPriceTv.text = "￥$sumPrice  BV$sumBv"
            Log.i("totalAmount", "----BV$sumBv     ￥$sumPrice")




            holder.nameTv.text = data[position].businessname
            holder.recyclerView.run {
                layoutManager = LinearLayoutManager(context)
                adapter = MyChildAdapter(context, detailList)
            }


        }
    }


    inner class MyChildAdapter(
        context: Context,
        var dataList: MutableList<ShoppingCarListBean.CartListBean.DetailsBean>
    ) :
        RecyclerView.Adapter<MyChildAdapter.MyChildHolder>() {
        val layoutInflater: LayoutInflater = LayoutInflater.from(context)

        inner class MyChildHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var iv = itemView.findViewById<ImageView>(R.id.iv)
            var titleTv = itemView.findViewById<TextView>(R.id.titleTv)
            var specificationTv = itemView.findViewById<TextView>(R.id.specificationTv)
            var bvPriceTv = itemView.findViewById<TextView>(R.id.bvPriceTv)
            var memberPriceTv = itemView.findViewById<TextView>(R.id.memberPriceTv)
            var selectTv = itemView.findViewById<TextView>(R.id.selectTv)
            var memberPrice = itemView.findViewById<TextView>(R.id.memberPrice)
            var numEt = itemView.findViewById<EditText>(R.id.numEt)
            var jiaIv = itemView.findViewById<ImageView>(R.id.jiaIv)
            var jianIv = itemView.findViewById<ImageView>(R.id.jianIv)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyChildHolder {
            var view =
                layoutInflater.inflate(R.layout.new_shopping_car_child_item_layout, parent, false)
            return MyChildHolder(view)
        }

        override fun getItemCount(): Int = when (dataList) {
            null -> 0
            else -> dataList.size
        }

        override fun onBindViewHolder(holder: MyChildHolder, position: Int) {
            holder.iv.load(dataList[position].smallimgurl)
            holder.titleTv.text = dataList[position].name
            holder.numEt.setText(dataList[position].number.toString())
            holder.numEt.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (s.toString() != null && s.toString() != "") {
                        if (s.toString().startsWith("0")) {
                            holder.numEt.setText("1")
                            updateShoppingCarId = dataList[position].shopcarid
                            updateShoppingCarNum = 1
                            showProgress()
                            presenter.editShoppingCar(
                                updateShoppingCarId.toString(),
                                updateShoppingCarNum.toString()
                            )
                        } else {
                            updateShoppingCarId = dataList[position].shopcarid
                            updateShoppingCarNum = s.toString().toInt()
                            showProgress()
                            presenter.editShoppingCar(
                                updateShoppingCarId.toString(),
                                updateShoppingCarNum.toString()
                            )
                        }
                    }
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                }

            })
            holder.specificationTv.text = dataList[position].typename
            holder.bvPriceTv.text = dataList[position].bvprice + "BV"
            if (ifHui == "1") {
                holder.memberPrice.visibility = VISIBLE
                holder.memberPriceTv.text = "￥" + dataList[position].hyprice
            } else {
                holder.memberPrice.visibility = GONE
                holder.memberPriceTv.text = "￥" + dataList[position].price
            }
            holder.selectTv.isSelected = dataList[position].isSelectState
            holder.selectTv.setOnClickListener {
                dataList[position].isSelectState = !dataList[position].isSelectState
//                isSelectAll = dataList[position].isSelectState
//                selectAllCb.isSelected = isSelectAll
                if (!dataList[position].isSelectState) {
                    isSelectAll = dataList[position].isSelectState
                    selectAllCb.isSelected = isSelectAll
                }
                Log.i(
                    "selectedState",
                    "---------" + data[0].isSelectAll + "-----" + dataList[position].isSelectState
                )
                shoppingCarRecyclerView.adapter?.notifyDataSetChanged()
            }
            holder.jiaIv.setOnClickListener {
                //添加商品数量
                var number = dataList[position].number
                var shopcarid = dataList[position].shopcarid
                number += 1
                updateShoppingCarId = shopcarid
                updateShoppingCarNum = number
                showProgress()
                presenter.editShoppingCar(shopcarid.toString(), number.toString())

            }
            holder.jianIv.setOnClickListener {
                var number = dataList[position].number
                var shopcarid = dataList[position].shopcarid
                number -= 1
                if (number == 0) return@setOnClickListener
                updateShoppingCarId = shopcarid
                updateShoppingCarNum = number
                showProgress()
                presenter.editShoppingCar(shopcarid.toString(), number.toString())
            }
        }
    }


    var selectType = 1
    override fun initData() {
        pageNum = 1
        data.clear()
        shoppingCarRecyclerView.adapter?.notifyDataSetChanged()
        showProgress()
        presenter.getShoppingCarList()
    }

    override fun initEvent() {
        backIv.setOnClickListener { finish() }
        selectAllCb.setOnClickListener {
            if (data.size == 0) {
                ToastUtils.showLongToast("暂无商品")
                return@setOnClickListener
            }
            isSelectAll = !isSelectAll
            selectAllCb.isSelected = isSelectAll
            for (index in data.indices) {
                data[index].isSelectAll = isSelectAll
                var details = data[index].details
                for (indexO in details.indices) {
                    details[indexO].isSelectState = isSelectAll
                }
            }
            shoppingCarRecyclerView.adapter?.notifyDataSetChanged()
        }
        toSettlementTv.setOnClickListener {

            //结算按钮
            var sumBv = 0.0
            var sumPrice = 0.0
            var shopCarIds = StringBuffer()
            for (index in 0 until data.size) {
                var details = data[index].details
                for (k in details.indices) {
                    if (details[k].isSelectState) {
                        var bvPrice = details[k].bvprice

                        sumBv += bvPrice.toDouble() * details[k].number
                        sumPrice += if (ifHui == "1") {
                            var hyPrice = details[k].hyprice
                            hyPrice.toDouble() * details[k].number
                        } else {
                            var price = details[k].price
                            price.toDouble() * details[k].number
                        }


//                        var bvPrice = details[k].bvprice
//                        var hyPrice = details[k].hyprice
                        shopCarIds.append("," + details[k].shopcarid)
//                        sumBv += bvPrice.toDouble() * details[k].number
//                        sumPrice += hyPrice.toDouble() * details[k].number
                    }
                }
            }
            if (selectType == 1) {//结算
                if (sumPrice == 0.0) {
                    ToastUtils.showLongToast("请选择要购买的商品")
                    return@setOnClickListener
                }
                totalPriceTv.text = "￥$sumPrice  BV$sumBv"
                Log.i("totalAmount", "----BV$sumBv     ￥$sumPrice")
                var substring = shopCarIds.substring(1)
                var intent = Intent(this, FillOrderActivity::class.java)
                intent.putExtra("shopCarIds", substring)
                startActivity(
                    intent
                )
                isSelectAll = false
                selectAllCb.isSelected = isSelectAll
                data.clear()
                totalPriceTv.text = "￥0.00    BV0.00"
                shoppingCarRecyclerView.adapter?.notifyDataSetChanged()
            } else {//删除
                if (sumPrice == 0.0) {
                    ToastUtils.showLongToast("请选择要删除的商品")
                    return@setOnClickListener
                }
                var shopCarIds = shopCarIds.substring(1)
                selShoppingCarIds = shopCarIds
                showProgress()
                presenter.deleteShoppingCar()

            }
        }
        rightIv.setOnClickListener {
            isSelectAll = false
            selectAllCb.isSelected = isSelectAll
            for (index in data.indices) {
                data[index].isSelectAll = false
                var details = data[index].details
                for (indexO in details.indices) {
                    details[indexO].isSelectState = false
                }
            }
            shoppingCarRecyclerView.adapter?.notifyDataSetChanged()

            if (selectType == 1) {//删除
                selectType = 2
                total.visibility = INVISIBLE
                totalPriceTv.visibility = INVISIBLE
                toSettlementTv.text = getString(R.string.delete)
            } else {
                selectType = 1
                total.visibility = VISIBLE
                totalPriceTv.visibility = VISIBLE
                toSettlementTv.text = getString(R.string.toSettlement)
            }
        }
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(top).init()
    }

    override fun editFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun getFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun deleteSuccess() {
        toast("删除成功")
        isSelectAll = false
        selectAllCb.isSelected = isSelectAll
        if (selectType == 1) {//删除
            toSettlementTv.text = getString(R.string.toSettlement) + "(0)"
        } else {
            toSettlementTv.text = getString(R.string.delete) + "(0)"
        }
        hideProgress()
        presenter.getShoppingCarList()
    }

    override fun deleteFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun getShoppingCarIds(): String = selShoppingCarIds
    override fun editSuccess() {
        hideProgress()
        for (item in data) {
            var details = item.details
            for (childItem in details) {
                if (childItem.shopcarid == updateShoppingCarId) {
                    if (updateShoppingCarNum == 0) {
                        details.remove(childItem)
                    } else {
                        childItem.number = updateShoppingCarNum
                    }
                    shoppingCarRecyclerView.adapter?.notifyDataSetChanged()
                }
            }
        }
    }

    override fun getPage(): String = pageNum.toString()

    override fun getListSuccess(shoppingCarListBean: ShoppingCarListBean?) {
        hideProgress()
        springView.onFinishFreshAndLoad()
        ifHui = shoppingCarListBean?.ifhui!!
        var cartList = shoppingCarListBean?.cartList
        if (pageNum == 1) {
            data.clear()
            if (cartList == null || cartList.size == 0) {
                noDataIv.visibility = VISIBLE
            } else {
                noDataIv.visibility = GONE
            }
        }
        data.addAll(cartList!!)

//        for (index in data.indices) {
//            data[index].isSelectAll = false
//        }
        Log.i("dasdasdsada", "=======" + data.size)
        shoppingCarRecyclerView.adapter?.notifyDataSetChanged()
    }

    override fun onLoadmore() {
        pageNum += 1
        presenter.getShoppingCarList()
    }

    override fun onRefresh() {
        pageNum = 1
        presenter.getShoppingCarList()
    }

}
